<script setup lang="ts">
  import { ref, onMounted } from 'vue'
  import tips from './components/tips.vue'
  import { getSiteList } from '@/api/asset/car-stock'
  import { onShow } from '@dcloudio/uni-app'
  import {
    carStockStatistics,
    databoardcarUseRate,
    databoardselectStoreRevenue,
    databoardorderRevenue,
    databoardorderCounts,
  } from '@/api/home/databoard'
  // 组件
  import storeInventory from './chart/storeInventory.vue'
  import storePie from './chart/storePie.vue'
  import carOccupy from './chart/carOccupy.vue'
  import carLinechart from './chart/carLinechart.vue'
  import orderNum from './chart/orderNum.vue'
  import summaryNavFilter from '../revenue-summary/components/summary-nav-filter.vue'
  import CardWrap from '../revenue-summary/components/card/card-wrap.vue'
  import { onLoad } from '@dcloudio/uni-app'
  import dayjs from 'dayjs'
  import { carSeriesRevenueRank, carModelRevenueRank } from '@/api/revenue/assets'

  onLoad((options: any) => {
    if (options.siteId) {
      dataAmount.value.amount2.siteId = options.siteId
      dataAmount.value.amount3.siteId = options.siteId
      dataAmount.value.amount4.siteId = options.siteId
      dataAmount.value.amount5.siteId = options.siteId
      dataAmount.value.amount6.siteId = options.siteId
    }
  })
  const dataAmount = ref({
    amount2: { siteId: '', siteName: '全部门店', data: [] },
    amount3: { siteId: '', siteName: '全部门店', time: 1, data: [] },
    amount4: { siteId: '', siteName: '全部门店', data: [] },
    amount5: { siteId: '', channelType: '', siteName: '全部门店', time: 2, data: [] },
    amount6: { siteId: '', channelType: '', siteName: '全部门店', time: 2, data: [] },
  })
  // 门店-下拉框
  const siteList = ref([])
  const getDefaultSite = () => {
    getSiteList({ siteStatusList: ['10'] }).then((res) => {
      if (res.code == 200) {
        siteList.value = res.result
        siteList.value.unshift({ siteName: '全部门店', id: '全部门店' })
      }
    })
  }
  // 车辆库存
  const rendercarStockStatistics = () => {
    carStockStatistics({
      siteId: dataAmount.value.amount2.siteId,
    }).then((res) => {
      if (res.code == 200) {
        dataAmount.value.amount2.data = res.result || {}
      }
    })
  }
  //车辆出租率
  const renderdataboardcarUseRate = () => {
    databoardcarUseRate({
      siteId: dataAmount.value.amount3.siteId,
      carRateTimeType: dataAmount.value.amount3.time,
    }).then((res) => {
      if (res.code == 200) {
        dataAmount.value.amount3.data = res.result
      }
    })
  }
  //门店预计收益
  const renderdataboardselectStoreRevenue = () => {
    databoardselectStoreRevenue({
      siteId: dataAmount.value.amount4.siteId,
    }).then((res) => {
      if (res.code == 200) {
        if (res.result.shortOrder) {
          dataAmount.value.amount4.data = res.result.shortOrder
        }
      }
    })
  }

  const orderIncomeList = ref<any[]>([])
  //订单收益统计
  const renderdataboardorderRevenue = () => {
    databoardorderRevenue({
      incomeDateType: dataAmount.value.amount5.time,
      siteId: dataAmount.value.amount5.siteId,
      channelType: dataAmount.value.amount5.channelType,
    }).then((res) => {
      if (res.code == 200) {
        res.result?.model.forEach((item, index) => {
          item.tmpName = item.name
        })
        res.result?.series.forEach((item, index) => {
          item.tmpName = item.seriesName
        })
        dataAmount.value.amount5.data = res.result || {}
        orderIncomeList.value = res.result?.series || []
      }
    })
  }
  //订单量统计
  const orderNumList = ref<any[]>([])
  const renderdataboardorderCounts = () => {
    databoardorderCounts({
      incomeDateType: dataAmount.value.amount6.time,
      siteId: dataAmount.value.amount6.siteId,
      channelType: dataAmount.value.amount6.channelType,
    }).then((res) => {
      if (res.code == 200) {
        res.result?.model.forEach((item, index) => {
          item.tmpName = item.name
        })
        res.result?.series.forEach((item, index) => {
          item.tmpName = item.seriesName
        })
        dataAmount.value.amount6.data = res.result || {}
        orderNumList.value = res.result?.series || []
      }
    })
  }
  onMounted(() => {
    getDefaultSite() //门店
    rendercarStockStatistics() //车辆库存
    renderdataboardcarUseRate() //车辆出租率
    renderdataboardselectStoreRevenue() // 门店预计收益
    renderdataboardorderRevenue() //订单收益统计
    renderdataboardorderCounts() // 订单量统计
  })
  onShow(() => {
    uni.$emit('onShow')
  })
  const changeSitlist = (status, id, val, option) => {
    if (option.id === '全部门店' || option.orgId === '全部机构') {
      dataAmount.value[id].siteId = ''
    } else {
      dataAmount.value[id].siteId = option.id || option.orgId
    }
    dataAmount.value[id].siteName = option.siteName
    if (status === '库存统计') {
      rendercarStockStatistics() //车辆库存
    } else if (status === '车辆出租率统计') {
      renderdataboardcarUseRate() //车辆出租率
    } else if (status === '门店预计收益') {
      renderdataboardselectStoreRevenue() // 门店预计收益
    } else if (status === '订单收益统计') {
      orderRevenueTabIndex.value = 0
      renderdataboardorderRevenue() //订单收益统计
    } else if (status === '订单量统计') {
      orderNumTabIndex.value = 0
      renderdataboardorderCounts() // 订单量统计
    }
  }
  const changeTime = (status, id, val, option) => {
    dataAmount.value[id].time = option.value
    if (status === '车辆出租率统计') {
      renderdataboardcarUseRate() //车辆出租率
    } else if (status === '订单收益统计') {
      orderRevenueTabIndex.value = 0
      renderdataboardorderRevenue() //订单收益统计
    } else if (status === '订单量统计') {
      orderNumTabIndex.value = 0
      renderdataboardorderCounts() // 订单量统计
    }
  }
  const changeChannel = (status, id, val, option) => {
    dataAmount.value[id].channelType = option.value

    if (status === '订单收益统计') {
      orderRevenueTabIndex.value = 0
      renderdataboardorderRevenue() //订单收益统计
    } else if (status === '订单量统计') {
      orderNumTabIndex.value = 0
      renderdataboardorderCounts() // 订单量统计
    }
  }
  const carLineTooltip = ref({
    name: '出租率',
    tip: '出租率=出租租日/总租日 * 100%',
  })
  const storeLineTooltip = ref({
    name: '自驾短租未来30天预计收益(含当天)',
    tip: '仅计算订单的车辆租金',
    tipPlacement: 'top',
  })
  const orderRevenueTooltip = ref({
    name: '自驾短租收益趋势',
    tip: '仅计算订单账单中已确认的费用作为收益，不计算已作废的订单账单费用',
  })

  const orderRevenueTabIndex = ref(0)
  const orderNumTooltip = ref({
    name: '自驾短租订单量趋势',
    tip: '不计算借出、已处置的车辆',
  })

  const orderNumTabIndex = ref(0)
  const timeMap1 = ref([
    { label: '近1周', value: 1 },
    { label: '近1个月', value: 2 },
    { label: '近1年', value: 3 },
  ])
  const timeMap3 = ref([
    { label: '前后15天', value: 1 },
    { label: '近1年', value: 2 },
  ])

  // 车系/车型收益排行 ================================
  const columns: any = {
    0: [
      {
        label: '排名',
        dataIndex: 'index',
        minWidth: '60rpx',
      },
      {
        label: '车系',
        dataIndex: 'seriesName',
      },
      {
        label: '收益(元)',
        dataIndex: 'totalAmount',
        sort: true,
        sortField: 'totalAmount',
        defaultSort: true,
        defaultSortType: 'desc',
        minWidth: '120rpx',
        style: {
          color: '#3072f6',
        },
      },
      {
        label: '订单量(单)',
        dataIndex: 'count',
        sort: true,
        sortField: 'count',
        minWidth: '140rpx',
      },
      {
        label: '客单价(元)',
        dataIndex: 'amount',
        minWidth: '120rpx',
      },
    ],
    1: [
      {
        label: '排名',
        dataIndex: 'index',
        minWidth: '60rpx',
      },
      {
        label: '车型',
        dataIndex: 'name',
      },
      {
        label: '收益(元)',
        dataIndex: 'totalAmount',
        sort: true,
        sortField: 'totalAmount',
        defaultSort: true,
        defaultSortType: 'desc',
        minWidth: '120rpx',
        style: {
          color: '#3072f6',
        },
      },
      {
        label: '订单量(单)',
        dataIndex: 'count',
        sort: true,
        sortField: 'count',
        minWidth: '140rpx',
      },
      {
        label: '客单价(元)',
        dataIndex: 'amount',
        minWidth: '120rpx',
      },
    ],
  }
  const carLoading = ref(false)
  const isCurrent = ref(0)
  const carList = ref<any>({
    columns: columns[isCurrent.value],
    data: [],
  })
  const tabs = [
    {
      type: 'series',
      name: '按车系排行',
    },
    {
      type: 'model',
      name: '按车型排行',
    },
  ]
  const carListQueryParam = ref<any>({
    orderByType: 1,
    pageSize: 1000,
    pageNumber: 1,
    sortField: 'totalAmount',
    sortType: 'desc',
  })

  const loadCarList = (params: any = {}) => {
    carLoading.value = true
    if (isCurrent.value === 0) {
      carList.value.columns = columns[0]
      carSeriesRevenueRank(params)
        .then((res: any) => {
          carList.value.data = res.result.data
        })
        .finally(() => {
          carLoading.value = false
        })
    } else {
      carList.value.columns = columns[1]
      carModelRevenueRank(params)
        .then((res: any) => {
          carList.value.data = res.result.data
        })
        .finally(() => {
          carLoading.value = false
        })
    }
  }

  // 初始化车系车型列表数据
  const onQueryParamsChange = (params: any) => {
    carListQueryParam.value = {
      ...carListQueryParam.value,
      siteIdList: params.siteIdList,
      orderTimeQueryType: params.orderTimeQueryType,
      startTime: dayjs(params.startTime).format('YYYY-MM-DD 00:00:00'),
      endTime: dayjs(params.endTime).format('YYYY-MM-DD 23:59:59'),
      seriesIdList: params.seriesIdList,
      modelIdList: params.modelIdList,
    }

    loadCarList(carListQueryParam.value)
  }

  // 切换车系和车型
  const onClickCar = (index: number) => {
    isCurrent.value = index
    columns[index].forEach((item: any) => {
      if (item.sort && item.defaultSort) {
        item.sortType = 'desc'
      } else {
        item.sortType = ''
      }
    })

    carListQueryParam.value.sortField = 'totalAmount'
    carListQueryParam.value.sortType = 'desc'
  }

  const onHeaderSort = (item: any) => {
    if (carList.value.data.length == 0) return

    if (carListQueryParam.value.sortField != item.sortField) {
      const sortItem = columns[isCurrent.value].filter((item: any) => item.sortField == carListQueryParam.value.sortField)
      sortItem[0].sortType = ''
      if (sortItem[0].defaultSortType) {
        sortItem[0].defaultSortType = ''
      }
      carListQueryParam.value.sortType = ''
    }

    carListQueryParam.value.sortField = item.sortField

    if (item.sortField == 'totalAmount') {
      if (!carListQueryParam.value.sortType) {
        carListQueryParam.value.sortType = 'asc'
        item.sortType = 'asc'
      } else if (carListQueryParam.value.sortType == 'asc') {
        carListQueryParam.value.sortType = 'desc'
        item.sortType = 'desc'
      } else if (carListQueryParam.value.sortType == 'desc') {
        carListQueryParam.value.sortType = ''
        item.sortType = ''
      }
    }

    if (item.sortField == 'count') {
      if (!carListQueryParam.value.sortType) {
        carListQueryParam.value.sortType = 'asc'
        item.sortType = 'asc'
      } else if (carListQueryParam.value.sortType == 'asc') {
        carListQueryParam.value.sortType = 'desc'
        item.sortType = 'desc'
      } else if (carListQueryParam.value.sortType == 'desc') {
        carListQueryParam.value.sortType = ''
        item.sortType = ''
      }
    }

    loadCarList(carListQueryParam.value)
  }
</script>

<template>
  <scroll-view scroll-y class="databoard">
    <view class="ve-card-header-border-line-content mr0"></view>

    <view class="plr24">
      <tips
        name="库存统计"
        :siteList="siteList"
        :slotStatus="true"
        @onchangeSite="(val, option) => changeSitlist('库存统计', 'amount2', val, option)"
      >
        <template #tips>
          <storeInventory
            pagePath="pages/databoard/index"
            v-show="dataAmount.amount2.siteName === '全部门店'"
            :amount="dataAmount.amount2.data?.carCountDto"
          />
          <storePie
            v-show="dataAmount.amount2.siteName !== '全部门店'"
            :amount="dataAmount.amount2.data?.carCountDto"
            :status="dataAmount.amount2.siteName === '全部门店' ? false : true"
          />
          <view class="ve-card-header-border-line-content"></view>
          <carOccupy
            :data="dataAmount.amount2"
            :amount="dataAmount.amount2.data?.carOccupancyRate?.filter((item: any) => item.name != '已丢失')"
            :num="dataAmount.amount2.data?.totalCount"
          />
        </template>
      </tips>
    </view>

    <view class="plr24">
      <tips
        name="车辆出租率统计"
        :siteList="siteList"
        :slotStatus="true"
        @onchangeSite="(val, option) => changeSitlist('车辆出租率统计', 'amount3', val, option)"
        @onchangeTime="(val, option) => changeTime('车辆出租率统计', 'amount3', val, option)"
        :timeMap="timeMap3"
        showTimeselect
        :timeValue="0"
      >
        <template #tips>
          <carLinechart
            key="carHire"
            pagePath="pages/databoard/index"
            canvasId="carHire"
            :amount="dataAmount.amount3.data"
            :carLineTooltip="carLineTooltip"
          />
        </template>
      </tips>
    </view>

    <view class="plr24">
      <tips
        name="门店预计收益"
        :siteList="siteList"
        :slotStatus="true"
        @onchangeSite="(val, option) => changeSitlist('门店预计收益', 'amount4', val, option)"
      >
        <template #tips>
          <carLinechart
            key="storeHire"
            pagePath="pages/databoard/index"
            canvasId="storeHire"
            :amount="dataAmount.amount4.data"
            :carLineTooltip="storeLineTooltip"
          />
        </template>
      </tips>
    </view>

    <view class="plr24">
      <tips
        name="订单收益统计"
        direction="column"
        :siteList="siteList"
        :slotStatus="true"
        :showTimeselect="true"
        :showChannel="true"
        @onchangeSite="(val, option) => changeSitlist('订单收益统计', 'amount5', val, option)"
        @onchangeTime="(val, option) => changeTime('订单收益统计', 'amount5', val, option)"
        @onchangeChannel="(val, option) => changeChannel('订单收益统计', 'amount5', val, option)"
        :timeMap="timeMap1"
        :channelValue="dataAmount.amount5.channelType"
      >
        <template #tips>
          <!-- 自驾短租收益趋势 -->
          <orderNum
            key="orderRevenue"
            pagePath="pages/databoard/index"
            :amount="dataAmount.amount5.data?.channel"
            canvasId="orderRevenue"
            :orderNumTooltip="orderRevenueTooltip"
            :total="dataAmount.amount5.data?.total"
          />
        </template>
      </tips>
    </view>

    <view class="plr24">
      <tips
        name="订单量统计"
        direction="column"
        :siteList="siteList"
        :slotStatus="true"
        :showTimeselect="true"
        :showChannel="true"
        @onchangeSite="(val, option) => changeSitlist('订单量统计', 'amount6', val, option)"
        @onchangeTime="(val, option) => changeTime('订单量统计', 'amount6', val, option)"
        @onchangeChannel="(val, option) => changeChannel('订单量统计', 'amount6', val, option)"
        :timeMap="timeMap1"
        :channelValue="dataAmount.amount6.channelType"
      >
        <template #tips>
          <orderNum
            key="orderNum"
            pagePath="pages/databoard/index"
            :amount="dataAmount.amount6.data?.channel"
            canvasId="orderNum"
            :orderNumTooltip="orderNumTooltip"
            :total="dataAmount.amount6.data?.total"
          />
        </template>
      </tips>
    </view>

    <CardWrap title="车系/车型收益排行">
      <view class="chart-radio-group flex mb-4">
        <view
          v-for="(tab, index) in tabs"
          :key="tab.name"
          class="chart-radio flex justify-center items-center text-base"
          :class="{ 'chart-active': index === isCurrent }"
          @click="onClickCar(index)"
        >
          {{ tab.name }}
        </view>
      </view>
      <!-- 筛选 -->
      <!-- 传入revenueRankingTab 代表当前是车系 series | model -->
      <summaryNavFilter
        ref="summaryNavFilterRef"
        :revenueRankingTab="tabs[isCurrent].type"
        @change="onQueryParamsChange"
        class="filter w-full"
      />

      <view class="car-box">
        <view v-if="carLoading" class="car-loading w-full flex justify-center items-center"> 数据加载中... </view>
        <table v-else class="w-full">
          <tr class="header">
            <th v-for="item in carList.columns" :key="item.name" @click="() => onHeaderSort(item)">
              <view class="flex items-center">
                <span>{{ item.label }}</span>
                <span class="car-header-item-sort ml-2" v-if="item.sort">
                  <ve-icon
                    :name="item.defaultSortType == 'asc' || item.sortType == 'asc' ? 'arrow_top_1' : 'arrow_top_0'"
                    width="20"
                    height="20"
                  ></ve-icon>
                  <ve-icon
                    :name="item.defaultSortType == 'desc' || item.sortType == 'desc' ? 'arrow_bottom_1' : 'arrow_bottom_0'"
                    width="20"
                    height="20"
                  ></ve-icon>
                </span>
              </view>
            </th>
          </tr>
          <tr class="body" v-if="carList.data.length == 0">
            <td class="no-data" colspan="5" style="text-align: center">
              <ve-empty />
            </td>
          </tr>
          <template v-else>
            <tr class="body" v-for="(item, index) in carList.data" :key="item.name">
              <td class="text-nowrap" v-for="column in carList.columns" :key="column.name">
                <view :style="{ width: column.width, minWidth: column.minWidth }" v-if="column.dataIndex == 'index'">{{ index + 1 }}</view>
                <view :style="{ width: column.width, minWidth: column.minWidth, ...column.style }" v-else>
                  {{ item[column.dataIndex] }}
                </view>
              </td>
            </tr>
          </template>
        </table>
      </view>
    </CardWrap>
    <ve-gap size="32"></ve-gap>
  </scroll-view>
</template>

<style lang="scss">
  .mr0 {
    margin: 0 !important;
  }
  .plr24 {
    padding: 0 24rpx;
  }
  .pt0 {
    padding-top: 0;
  }
  .staticstis-view {
    background: #fff;
    padding: 0 24rpx 32rpx 24rpx;
  }
  .ve-card-header-border-line-content {
    width: 100%;
    height: 2rpx;
    background-color: rgba(216, 216, 216, 0.3);
    margin: 32rpx 0;
  }

  .w-full {
    width: 100%;
  }
  .flex {
    display: flex;
  }
  .justify-center {
    justify-content: center;
  }
  .items-center {
    align-items: center;
  }
  .ml-2 {
    margin-left: 8rpx;
  }
  .text-base {
    font-size: 32rpx;
  }
  .text-nowrap {
    white-space: nowrap;
  }
  .truncate {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
  table {
    width: 100%;
    border-collapse: collapse;

    th,
    td {
      border-bottom: 1px solid rgb(160 160 160);
      padding: 20rpx 20rpx;
    }

    .header {
      background: #f2f3f5;
      font-weight: 500;
    }

    .body {
      font-weight: 400;
      .no-data {
        border-bottom: none;
      }
    }

    .header,
    .body {
      font-size: 24rpx;
      color: #1d2129;
    }
  }

  .databoard {
    overflow-x: hidden;
    background: #f7f8fa;
  }

  .car-box {
    width: 100%;
    overflow-x: auto;

    .car-header-item {
      background-color: #f2f3f5;
      padding: 20rpx 20rpx;

      &-content {
        display: flex;
        align-items: center;
      }

      &-sort {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
      }
    }
  }

  .filter {
    height: 48rpx;
  }

  .chart-radio-group {
    .chart-radio {
      height: 56rpx;
      font-weight: 400;
      color: #86909c;
      margin-right: 40rpx;

      &.chart-active {
        font-weight: 600;
        color: #3072f6;
        border-bottom: 4rpx solid #3072f6;
      }
    }
  }
</style>
